﻿using System;
using System.Collections;
using System.Collections.Generic;
using ApplicationGenerator.DataAccess;



namespace ApplicationGenerator.Lists.BusinessLogic
{
    public class HQLQuerryExecutor
    {
        public List<Dictionary<string, string>> GetRows(IConfigDetails configDetails, string hqlQuerry, string whereStatement)
        {
            string querry = hqlQuerry + whereStatement;
            IList querryResults = HQLManager.ExecuteHQL(querry);
            object[] columns;

            List<Dictionary<string, string>> resultRows = new List<Dictionary<string, string>>();
            Dictionary<string, string> resultColumn = null;

            if (querryResults == null)
            {
                return resultRows;
            }

            for (int nRow = 0; nRow < querryResults.Count; nRow++)
            {
                resultColumn = new Dictionary<string, string>();
                columns = (querryResults[nRow] is object[]) ? querryResults[nRow] as object[] : new object[] { querryResults[nRow] };
                for (int nColumn = 0; nColumn < configDetails.ConfiguredColumns.Count; nColumn++)
                {
                    if (IsConfiguredColumn(configDetails, nColumn))
                    {
                        resultColumn[GetConfiguredColumnDisplayName(configDetails, nColumn)] = Convert.ToString(columns[nColumn]);
                    }
                }

                resultRows.Add(resultColumn);
            }

            return resultRows;
        }

        private string GetConfiguredColumnDisplayName(IConfigDetails configDetails, int columnIndex)
        {
            foreach (var configuredColumn in configDetails.ConfiguredColumns)
            {
                if (configuredColumn.Column.Name == configDetails.AvailableColumns[columnIndex].Name)
                {
                    return configuredColumn.DisplayName;
                }
            }

            throw new Exception("Brak kolumny w konfiguracji");
        }

        private bool IsConfiguredColumn(IConfigDetails configDetails, int columnIndex)
        {
            foreach (var configuredColumn in configDetails.ConfiguredColumns)
            {
                if (configuredColumn.Column.Name == configDetails.AvailableColumns[columnIndex].Name)
                {
                    return true;
                }
            }

            return false;
        }

    }
}
